#include "widget.h"
#include "ui_widget.h"
#include <QHostAddress>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    //分配空间，指定父对象
    m_UdpSocket = new QUdpSocket(this);
    //绑定
   // m_UdpSocket->bind(8888);


    setWindowTitle("Port 8888");

    //加入某个组播 组播地址D类地址
    m_UdpSocket->bind(QHostAddress::AnyIPv4, 8888);
    m_UdpSocket->joinMulticastGroup(QHostAddress("224.0.0.2"));
     //m_UdpSocket->leaveMulticastGroup();//退出组播
    //当对方发送信号过来
    connect(m_UdpSocket,&QUdpSocket::readyRead,this,&Widget::dealMsg);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::dealMsg()
{
    //读取对方发送的数据
    char buf[1024] ={0};
    QHostAddress clientAddr;
    quint16 port;
    qint64 len = m_UdpSocket->readDatagram(buf,sizeof(buf), &clientAddr, &port);
    if(len >0)
    {
         //格式化
        QString str =QString("[%1:%2]>> %3").arg(clientAddr.toString()).arg(port).arg(buf);
        ui->textEdit->append(str);
    }
}

void Widget::on_buttonSend_clicked()
{
    //发送数据
    QString ip = ui->lineEditIP->text();
    qint16 port = ui->lineEditPort->text().toInt();
    //获取编辑区的内容
    QString str = ui->textEdit->toPlainText();
    m_UdpSocket->writeDatagram(str.toUtf8().data(),QHostAddress(ip),port);
}
